package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zbkj.common.constants.AgentConstants;
import com.zbkj.common.constants.BrokerageRecordConstants;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.*;
import com.zbkj.common.model.city.CityRegionEntity;
import com.zbkj.common.model.order.MerchantOrder;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.user.UserAddress;
import com.zbkj.common.model.user.UserBrokerageRecord;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.response.AgentUserRegionItemResponse;
import com.zbkj.common.response.AgentUserRegionResponse;
import com.zbkj.common.response.SystemAdminAgentCityResponse;
import com.zbkj.common.response.UserAgentPageDataResponse;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.PreOrderInfoDetailVo;
import com.zbkj.service.dao.UserAgentDao;
import com.zbkj.service.service.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description UserAgentServiceImpl 接口实现
* @date 2025-07-02
*/
@Service
public class UserAgentServiceImpl extends ServiceImpl<UserAgentDao, UserAgent> implements UserAgentService {

    @Resource
    private UserAgentDao dao;

    @Resource
    private SystemAdminService systemAdminService;

    @Autowired
    private BrandAgentItemsService brandAgentItemsService;

    @Autowired
    private BrandAgentRegionService brandAgentRegionService;

    @Autowired
    private AgentCategoryService agentCategoryService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private AgentConfigService agentConfigService;

    @Autowired
    private BrandAgentService brandAgentService;

    @Autowired
    private UserAgentService userAgentService;

    @Autowired
    private CityRegionService cityRegionService;

    @Autowired
    private UserService userService;

    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private MerchantService merchantService;
//    @Autowired
//    private CityRegionService cityRegionService;

    @Override
    public Boolean create(UserAgentSaveRequest userAgentSaveRequest) {
        UserAgent userAgent = new UserAgent();
        BeanUtils.copyProperties(userAgentSaveRequest, userAgent, "id");
        boolean save = save(userAgent);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询用户代理关系表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<UserAgent>
     * @author dazongzi
     * @since 2025-07-02
     */
    @Override
    public List<UserAgentPageDataResponse> getList(UserAgentSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 UserAgent 类的多条件查询
        LambdaQueryWrapper<UserAgent> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.orderByDesc(UserAgent::getCreateTime);
        List<UserAgent> userAgents = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<UserAgentPageDataResponse> userAgentResponses = new ArrayList<>();

        userAgents.stream().forEach(x->{
            UserAgentPageDataResponse userAgentResponse = new UserAgentPageDataResponse();
            BeanUtils.copyProperties(x, userAgentResponse);
            userAgentResponses.add(userAgentResponse);
        });
        return userAgentResponses;
    }

    @Override
    public UserAgent getByUserId(Integer agentUserId, Integer id) {
        return getOne(new LambdaQueryWrapper<UserAgent>().eq(UserAgent::getUserId, agentUserId).eq(UserAgent::getSystemAdminId, id));
    }
    @Override
    public UserAgent getAdminUserId( Integer adminId) {
        return getOne(new LambdaQueryWrapper<UserAgent>().eq(UserAgent::getIsDel, 0).eq(UserAgent::getSystemAdminId, adminId));
    }

    @Override
    public AgentUserRegionResponse getCurAgentUserRegion() {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        List<UserAgent> userAgentList = getListByAdminId(currentUser.getId());
        if (CollUtil.isEmpty(userAgentList)) {
            // 如果当前用户是品牌商登陆人
            return null;
        }

        List<AgentUserRegionItemResponse> cityList = new ArrayList<>();
        for (UserAgent userAgent : userAgentList) {
            List<String> nameList = new ArrayList<>();
            List<String> idList = new ArrayList<>();
            if (StrUtil.isNotBlank(userAgent.getProvinceId())) {
                idList.add(userAgent.getProvinceId());
                nameList.add(userAgent.getProvince());
            }
            if (StrUtil.isNotBlank(userAgent.getCityId())) {
                idList.add(userAgent.getCityId());
                nameList.add(userAgent.getCity());
            }
            if (StrUtil.isNotBlank(userAgent.getDistrictId())) {
                idList.add(userAgent.getDistrictId());
                nameList.add(userAgent.getDistrict());
            }
            if (StrUtil.isNotBlank(userAgent.getStreetId())) {
                idList.add(userAgent.getStreetId());
                nameList.add(userAgent.getStreet());
            }
            idList = idList.stream().distinct().collect(Collectors.toList());
            AgentUserRegionItemResponse agentUserRegionItemResponse = new AgentUserRegionItemResponse();
            agentUserRegionItemResponse.setCityIdList(idList);
            agentUserRegionItemResponse.setAgentLevel(userAgent.getAgentLevel());
            agentUserRegionItemResponse.setCommunity(userAgent.getCommunity());
            agentUserRegionItemResponse.setTribe(userAgent.getTribe());
            if (idList.size() == 4) {
                // 街道级别，下面是社区
                agentUserRegionItemResponse.setDistrict(userAgent.getStreet());
                agentUserRegionItemResponse.setDistrictId(userAgent.getStreetId());
            }
            if (StrUtil.isNotBlank(userAgent.getTribe())) {
                nameList.add(userAgent.getTribe());
            }
            if (StrUtil.isNotBlank(userAgent.getCommunity())) {
                nameList.add(userAgent.getCommunity());
            }
            agentUserRegionItemResponse.setAddress(CollUtil.join(nameList, "/"));
            cityList.add(agentUserRegionItemResponse);
        }
        AgentUserRegionResponse agentUserRegionResponse = new AgentUserRegionResponse();
        agentUserRegionResponse.setCityList(cityList);
        return agentUserRegionResponse;
    }

    @Override
    public List<UserAgent> getByRegion(AgentCalcRequest agentCalcRequest, int agentLevel) {
        LambdaQueryWrapper<UserAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(UserAgent::getAgentLevel, agentLevel);
        switch (agentLevel) {
            case 1:
                checkWrapper.eq(UserAgent::getProvinceId, agentCalcRequest.getProvinceId());
                break;
            case 2:
                checkWrapper.eq(UserAgent::getCityId, agentCalcRequest.getCityId());
                break;
            case 3:
                checkWrapper.eq(UserAgent::getDistrictId, agentCalcRequest.getDistrictId());
                break;
        }
        if(ObjectUtils.isNotEmpty(agentCalcRequest.getBrandId())){
            checkWrapper.eq(UserAgent::getBrandId, agentCalcRequest.getBrandId());
        }
        if(ObjectUtils.isNotEmpty(agentCalcRequest.getMerId())){
            checkWrapper.eq(UserAgent::getMerId, agentCalcRequest.getMerId());
        }
        checkWrapper.eq(UserAgent::getIsDel, 0);
        checkWrapper.orderByAsc(UserAgent::getCreateTime);
        return list(checkWrapper);
    }

    /**
     * 获取省市区佣金比例
     *
     * @param orderDetail
     * @param detailVo
     * @param addressId
     * @param categorySn
     */
    @Override
    public void getAgentUserScale(OrderDetail orderDetail, PreOrderInfoDetailVo detailVo, Integer addressId, String categorySn) {
        AgentCategory agentCategory = agentCategoryService.getIdBySn(categorySn);
        if (ObjectUtils.isEmpty(agentCategory)) {
            log.warn("查询不到代理分类，无法进行分佣");
            return;
        }
        // 平台给当前商户设置的分成比例
        AgentConfigItems agentConfigItems = agentConfigService.getPlatformCategotysBrokerage(agentCategory.getId());
        // 判断是否为空
        if (ObjectUtils.isEmpty(agentConfigItems)) {
            return;
        }

        UserAddress userAddress = userAddressService.getById(addressId);

        AgentCalcRequest agentCalcRequest = new AgentCalcRequest();
        agentCalcRequest.setProvince(userAddress.getProvince());
        agentCalcRequest.setProvinceId(userAddress.getProvinceId());
        agentCalcRequest.setCity(userAddress.getCity());
        agentCalcRequest.setCityId(userAddress.getCityId());
        agentCalcRequest.setDistrict(userAddress.getDistrict());
        agentCalcRequest.setDistrictId(userAddress.getDistrictId());
        agentCalcRequest.setCommunity(null);
        agentCalcRequest.setStreet(userAddress.getStreet());
        agentCalcRequest.setDetail(userAddress.getDetail());
        agentCalcRequest.setBrandId(BrandUtil.getBrandIdByUrl());
        agentCalcRequest.setAgentConfigCategoryId(agentCategory.getId()); // 默认商品

        // 代理人
        TreeMap<Integer, BigDecimal> levelBrokerageMap = new TreeMap<>();
        for (int level = 1; level <= 5; level++) {
            // 根据地区获取佣金设置比例
            getAgentList(agentCalcRequest, level, levelBrokerageMap);
            switch (level) {
                case 1:
                    orderDetail.setProvinceBrokerageScale(levelBrokerageMap.get(level));
                    break;
                case 2:
                    orderDetail.setCityBrokerageScale(levelBrokerageMap.get(level));
                    break;
                case 3:
                    orderDetail.setDistrictBrokerageScale(levelBrokerageMap.get(level));
                    break;
                case 4:
                    orderDetail.setStreetBrokerageScale(levelBrokerageMap.get(level));
                    break;
                case 5:
                    orderDetail.setCommunityBrokerageScale(levelBrokerageMap.get(level));
                    break;
            }
        }
    }

    /**
     * 生成省市区代理的佣金记录（支付后）
     * @param brokerageRecordList
     * @param merchantOrder
     * @param orderDetailList
     * @param categorySn
     */
    @Override
    public void addAgentUserBrokerageRecord(List<UserBrokerageRecord> brokerageRecordList, MerchantOrder merchantOrder,
                                            List<OrderDetail> orderDetailList, String categorySn) {
        AgentCategory agentCategory = agentCategoryService.getIdBySn(categorySn);
        if (ObjectUtils.isEmpty(agentCategory)) {
            log.warn("查询不到代理分类，无法进行分佣");
            return;
        }
        BigDecimal provinceBrokerageFree = BigDecimal.ZERO;
        BigDecimal cityBrokerageFree = BigDecimal.ZERO;
        BigDecimal districtBrokerageFree = BigDecimal.ZERO;
        BigDecimal streetBrokerageFree = BigDecimal.ZERO;
        BigDecimal communityBrokerageFree = BigDecimal.ZERO;

        AgentCalcRequest agentCalcRequest = new AgentCalcRequest();
        agentCalcRequest.setProvince(merchantOrder.getProvince());
        agentCalcRequest.setProvinceId(merchantOrder.getProvinceId());
        agentCalcRequest.setCity(merchantOrder.getCity());
        agentCalcRequest.setCityId(merchantOrder.getCityId());
        agentCalcRequest.setDistrict(merchantOrder.getDistrict());
        agentCalcRequest.setDistrictId(merchantOrder.getDistrictId());
        agentCalcRequest.setCommunity(null);
        agentCalcRequest.setStreet(merchantOrder.getStreet());
        agentCalcRequest.setDetail(merchantOrder.getUserAddress());
        agentCalcRequest.setBrandId(merchantService.getBrandId(merchantOrder.getMerId()));
        agentCalcRequest.setAgentConfigCategoryId(agentCategory.getId()); // 默认商品
        agentCalcRequest.setMerId(merchantOrder.getMerId());

        // 代理人
        List<UserAgent> list = new ArrayList<>();
        // 代理人
        TreeMap<Integer, BigDecimal> levelBrokerageMap = new TreeMap<>();
        for (int level = 1; level <= 5; level++) {
            // 根据地区获取佣金设置比例
            List<UserAgent> agentUserList = getAgentList(agentCalcRequest, level, levelBrokerageMap);
            CollUtil.addAll(list, agentUserList);
        }

        for (OrderDetail orderDetail : orderDetailList) {
            // 平台给当前商户设置的分成比例
            AgentConfigItems agentConfigItems = agentConfigService.getPlatformCategotysBrokerage(agentCategory.getId());
            BigDecimal detailPrice = (orderDetail.getIsSvip() && orderDetail.getIsPaidMemberProduct()) ? orderDetail.getVipPrice() : orderDetail.getPrice();
            // 可以分佣的金额=订单金额（可能需要减去优惠券，邮费）
            BigDecimal totalAmount = detailPrice.multiply(new BigDecimal(orderDetail.getPayNum().toString()))
                    .subtract(orderDetail.getMerCouponPrice());
            // 商户用于分佣的金额(总平台给商户分配的)
            BigDecimal totalAmountBrand = totalAmount.multiply(agentConfigItems.getBrokerage())
                    .divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);

            // 省级代理
            BigDecimal provinceBrokerageScale = orderDetail.getProvinceBrokerageScale();
            if (ObjectUtil.isNotNull(provinceBrokerageScale) && provinceBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal acquired = getAgentAcquiredFee(totalAmountBrand, provinceBrokerageScale, orderDetail.getCityBrokerageScale());
                orderDetail.setProvinceBrokerageFree(acquired);
                provinceBrokerageFree.add(acquired);
                totalAmountBrand = totalAmountBrand.subtract(acquired);
            }

            // 市级代理
            BigDecimal cityBrokerageScale = orderDetail.getCityBrokerageScale();
            if (ObjectUtil.isNotNull(cityBrokerageScale) && cityBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal acquired = getAgentAcquiredFee(totalAmountBrand, cityBrokerageScale, orderDetail.getDistrictBrokerageScale());
                orderDetail.setCityBrokerageFree(acquired);
                cityBrokerageFree.add(acquired);
                totalAmountBrand = totalAmountBrand.subtract(acquired);
            }

            // 区级代理
            BigDecimal districtBrokerageScale = orderDetail.getDistrictBrokerageScale();
            if (ObjectUtil.isNotNull(districtBrokerageScale) && districtBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal acquired = getAgentAcquiredFee(totalAmountBrand, districtBrokerageScale, orderDetail.getStreetBrokerageScale());
                orderDetail.setDistrictBrokerageFree(acquired);
                districtBrokerageFree.add(acquired);
                totalAmountBrand = totalAmountBrand.subtract(acquired);
            }

            // 街道代理
            BigDecimal streetBrokerageScale = orderDetail.getStreetBrokerageScale();
            if (ObjectUtil.isNotNull(streetBrokerageScale) && streetBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal acquired = getAgentAcquiredFee(totalAmountBrand, streetBrokerageScale, orderDetail.getCommunityBrokerageScale());
                orderDetail.setStreetBrokerageFree(acquired);
                streetBrokerageFree.add(acquired);
                totalAmountBrand = totalAmountBrand.subtract(acquired);
            }

            // 小区代理
            BigDecimal communityBrokerageScale = orderDetail.getCommunityBrokerageScale();
            if (ObjectUtil.isNotNull(communityBrokerageScale) && communityBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal acquired = totalAmountBrand.multiply(communityBrokerageScale).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
                orderDetail.setCommunityBrokerageFree(acquired);
                communityBrokerageFree.add(acquired);
                totalAmountBrand = totalAmountBrand.subtract(acquired);
            }
        }

        merchantOrder.setProvinceBrokerageFree(provinceBrokerageFree);
        merchantOrder.setCityBrokerageFree(cityBrokerageFree);
        merchantOrder.setDistrictBrokerageFree(districtBrokerageFree);
        merchantOrder.setStreetBrokerageFree(streetBrokerageFree);
        merchantOrder.setCommunityBrokerageFree(communityBrokerageFree);

        TreeMap<Integer, BigDecimal> levelBrokerageMap1 = new TreeMap<>();
        levelBrokerageMap1.put(1, provinceBrokerageFree);
        levelBrokerageMap1.put(2, cityBrokerageFree);
        levelBrokerageMap1.put(3, districtBrokerageFree);
        levelBrokerageMap1.put(4, streetBrokerageFree);
        levelBrokerageMap1.put(5, communityBrokerageFree);

        // 获取佣金冻结期
        String freezingTime = systemConfigService.getValueByKey(SysConfigConstants.RETAIL_STORE_BROKERAGE_FREEZING_TIME);

        // 生成佣金记录
        List<UserBrokerageRecord> brokerageRecordList1 = list.stream().map(record -> {
            UserBrokerageRecord brokerageRecord = new UserBrokerageRecord();
            brokerageRecord.setUid(record.getUserId());
            brokerageRecord.setLinkNo(merchantOrder.getOrderNo());
            brokerageRecord.setLinkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER);
            brokerageRecord.setType(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD);
            brokerageRecord.setTitle(BrokerageRecordConstants.BROKERAGE_RECORD_TITLE_AGENT);
            BigDecimal price = levelBrokerageMap1.get(record.getAgentLevel());
            brokerageRecord.setPrice(price);
            brokerageRecord.setMark(StrUtil.format("获得推广佣金，分佣{}", price));
            brokerageRecord.setStatus(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE);
            brokerageRecord.setFrozenTime(Integer.valueOf(Optional.ofNullable(freezingTime).orElse("0")));
            brokerageRecord.setCreateTime(CrmebDateUtil.nowDateTime());
            brokerageRecord.setBrokerageLevel(0);
            return brokerageRecord;
        }).collect(Collectors.toList());
        brokerageRecordList.addAll(brokerageRecordList1);
    }

    @Override
    public List<SystemAdminAgentCityResponse> getCityListByUserId(Integer adminId) {
        LambdaQueryWrapper<UserAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(UserAgent::getIsDel, 0);
        checkWrapper.eq(UserAgent::getSystemAdminId, adminId);
        checkWrapper.orderByAsc(UserAgent::getId);
        List<UserAgent> userAgentList = userAgentService.list(checkWrapper);
        List<SystemAdminAgentCityResponse> responseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(userAgentList)) {
            for (UserAgent userAgent : userAgentList) {
                List<String> cityList = new ArrayList<>();
                if (StrUtil.isNotBlank(userAgent.getProvince())) {
                    cityList.add(userAgent.getProvince());
                }
                if (StrUtil.isNotBlank(userAgent.getCity())) {
                    cityList.add(userAgent.getCity());
                }
                if (StrUtil.isNotBlank(userAgent.getDistrict())) {
                    cityList.add(userAgent.getDistrict());
                }
                if (StrUtil.isNotBlank(userAgent.getStreet())) {
                    cityList.add(userAgent.getStreet());
                }
                if (StrUtil.isNotBlank(userAgent.getTribe())) {
                    cityList.add(userAgent.getTribe());
                }
                if (StrUtil.isNotBlank(userAgent.getCommunity())) {
                    cityList.add(userAgent.getCommunity());
                }
                if (CollUtil.isNotEmpty(cityList)) {
                    SystemAdminAgentCityResponse response = new SystemAdminAgentCityResponse();
                    String city = CollUtil.join(cityList, "/");
                    response.setCity(city);
                    responseList.add(response);
                }
            }
        }
        return responseList;
    }

    @Override
    public List<UserAgent> getListByAdminId(Integer adminId) {
        LambdaQueryWrapper<UserAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(UserAgent::getIsDel, 0);
        checkWrapper.eq(UserAgent::getSystemAdminId, adminId);
        checkWrapper.orderByAsc(UserAgent::getId);
        return userAgentService.list(checkWrapper);
    }

    @Override
    public void removeBySystemAdminId(Integer adminId) {
        dao.delete(Wrappers.<UserAgent>lambdaQuery().eq(UserAgent::getSystemAdminId, adminId));
    }

    @Override
    public List<CityRegionEntity> findVillageList(String disId, CityRegionEntity cityRegionEntity) {
        LambdaQueryWrapper<UserAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.select(UserAgent::getId, UserAgent::getTribe);
        checkWrapper.eq(UserAgent::getIsDel, 0);
        checkWrapper.eq(UserAgent::getStreetId, disId);
        checkWrapper.eq(UserAgent::getStreet, cityRegionEntity.getName());
        checkWrapper.orderByAsc(UserAgent::getId);
        List<UserAgent> list = userAgentService.list(checkWrapper);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(item -> {
                CityRegionEntity cityRegionEntityOut = new CityRegionEntity();
                cityRegionEntityOut.setId(Long.parseLong(item.getId().toString()));
                cityRegionEntityOut.setName(item.getTribe());
                cityRegionEntityOut.setLevel(5);
                cityRegionEntityOut.setDisId(item.getId().toString());
                return cityRegionEntityOut;
            }).collect(Collectors.toList());
        }
        return null;
    }


    private BigDecimal getAgentAcquiredFee(BigDecimal totalAmountBrand, BigDecimal provinceBrokerageScale, BigDecimal cityBrokerageScale) {
        // 下级是否要分佣
        if (ObjectUtil.isNotNull(cityBrokerageScale) && cityBrokerageScale.compareTo(BigDecimal.ZERO) > 0) {
            // 省代理占比减去市代理占比
            BigDecimal scale = provinceBrokerageScale.subtract(cityBrokerageScale);
            // 省代理获得的佣金
            BigDecimal acquired = totalAmountBrand.multiply(scale).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            return acquired;
        } else {
            // 全部给省级代理
            // 省代理获得的佣金
            BigDecimal acquired = totalAmountBrand.multiply(provinceBrokerageScale).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            return acquired;
        }
    }

    /**
     * 根据地区获取佣金设置比例
     *
     * @param agentCalcRequest
     * @param level
     * @param levelBrokerageMap
     * @return
     */
    private List<UserAgent> getAgentList(AgentCalcRequest agentCalcRequest, int level,
                                         TreeMap<Integer, BigDecimal> levelBrokerageMap) {
        if (level == AgentConstants.AGENT_LEVEL_1 || level == AgentConstants.AGENT_LEVEL_2 || level == AgentConstants.AGENT_LEVEL_3) {
            List<UserAgent> districtUserList = userAgentService.getByRegion(agentCalcRequest, level);
            if (CollUtil.isEmpty(districtUserList)) {
                // 要给区级代理分佣
                BrandAgentItems brandAgentItems = getDistrictAgentConfig(agentCalcRequest, level);
                if (null != brandAgentItems) {
                        levelBrokerageMap.put(level, brandAgentItems.getBrokerage());
                }
            }
            return districtUserList;
        }
        // 对于街道和小区的要特殊处理
        // 查询区下面的街道列表，通过街道列表去代理用户表查询符合条件的代理用户
        if (level == AgentConstants.AGENT_LEVEL_4) {
            // 查询区级代理比例设置列表
            List<BrandAgentRegion> list = brandAgentRegionService.getList(agentCalcRequest.getBrandId(), agentCalcRequest.getDistrictId(), AgentConstants.AGENT_LEVEL_3);
            if (CollUtil.isNotEmpty(list)) {
                List<Integer> brandAgentIds = list.stream().map(BrandAgentRegion::getBrandAgentId).distinct().collect(Collectors.toList());
                // 区以下的代理设置列表
                List<BrandAgentRegion> nextLevelList = brandAgentRegionService.getNextLevelNameList(agentCalcRequest.getBrandId(), brandAgentIds, AgentConstants.AGENT_LEVEL_4);
                if (CollUtil.isNotEmpty(nextLevelList)) {
                    // 示例：福海街道 福永街道 新安街道 西乡街道 沙井街道 松岗街道 石岩街道
                    // 匹配用户里面的街道
                    for (BrandAgentRegion brandAgentRegion : nextLevelList) {
                        if (agentCalcRequest.getStreet().contains(brandAgentRegion.getRegionName())
                                || agentCalcRequest.getDetail().contains(brandAgentRegion.getRegionName())) {
                            // 检查这个街道是否有对应的代理商，没有的话直接跳过
                            List<UserAgent> streetAgentUserList = this.getAgenUser(brandAgentRegion, level, agentCalcRequest);
                            if (CollUtil.isNotEmpty(streetAgentUserList)) {
                                BrandAgentItems brandAgentItems = getBrokerageConfig(brandAgentRegion, agentCalcRequest.getBrandId(), agentCalcRequest.getAgentConfigCategoryId());
                                    levelBrokerageMap.put(level, brandAgentItems != null ? brandAgentItems.getBrokerage() : BigDecimal.ZERO);
                                // 记录好分佣设置id
                                agentCalcRequest.setStreetOfBrandAgentItemsId(brandAgentItems != null ? brandAgentItems.getId() : 0);
                                agentCalcRequest.setStreetOfBrandAgentRegionId(brandAgentItems != null ? brandAgentItems.getAgentReginId() : 0);
                                return streetAgentUserList;
                            }
                        }
                    }
                }
            }
        }
        if (level == AgentConstants.AGENT_LEVEL_6) {
            // 查询区级代理比例设置列表
            Integer streetOfBrandAgentRegionId = agentCalcRequest.getStreetOfBrandAgentRegionId();
            if (ObjectUtil.isNotNull(streetOfBrandAgentRegionId) && streetOfBrandAgentRegionId > 0) {
                // 街道以下的代理设置列表
                List<BrandAgentRegion> nextLevelList = brandAgentRegionService.getNextLevelNameList(agentCalcRequest.getBrandId(),
                        Arrays.asList(streetOfBrandAgentRegionId), AgentConstants.AGENT_LEVEL_6);
                if (CollUtil.isNotEmpty(nextLevelList)) {
                    // 示例：竞舟社区 香樟社区 溪畔社区 文锦社区 政苑社区
                    // 匹配用户里面的小区
                    for (BrandAgentRegion brandAgentRegion : nextLevelList) {
                        if (agentCalcRequest.getDetail().contains(brandAgentRegion.getRegionName())) {
                            // 检查这个街道是否有对应的代理商，没有的话直接跳过
                            List<UserAgent> streetAgentUserList = this.getAgenUser(brandAgentRegion, level, agentCalcRequest);
                            if (CollUtil.isNotEmpty(streetAgentUserList)) {
                                BrandAgentItems brandAgentItems = getBrokerageConfig(brandAgentRegion, agentCalcRequest.getBrandId(), agentCalcRequest.getAgentConfigCategoryId());
                                levelBrokerageMap.put(level, brandAgentItems != null ? brandAgentItems.getBrokerage() : BigDecimal.ZERO);

                                // 记录好分佣设置id
                                agentCalcRequest.setCommunityOfBrandAgentItemsId(brandAgentItems != null ? brandAgentItems.getId() : 0);
                                agentCalcRequest.setCommunityOfBrandAgentRegionId(brandAgentItems != null ? brandAgentItems.getAgentReginId() : 0);
                                return streetAgentUserList;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private List<UserAgent> getAgenUser(BrandAgentRegion brandAgentRegion, int agentLevel, AgentCalcRequest agentCalcRequest) {
        LambdaQueryWrapper<UserAgent> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(UserAgent::getAgentLevel, agentLevel);
        switch (agentLevel) {
            case 4:
                // 街道
                checkWrapper.eq(UserAgent::getDistrictId, brandAgentRegion.getDistrictId());
                checkWrapper.eq(UserAgent::getStreet, brandAgentRegion.getRegionName());
                break;
            case 5:
                // 小区
                checkWrapper.eq(UserAgent::getDistrictId, brandAgentRegion.getDistrictId());
                checkWrapper.eq(UserAgent::getStreet, brandAgentRegion.getStreet());
                checkWrapper.eq(UserAgent::getCommunity, brandAgentRegion.getRegionName());
                break;
        }
        if (ObjectUtils.isNotEmpty(agentCalcRequest.getBrandId())) {
            checkWrapper.eq(UserAgent::getBrandId, agentCalcRequest.getBrandId());
        }
        if (ObjectUtils.isNotEmpty(agentCalcRequest.getMerId())) {
            checkWrapper.eq(UserAgent::getMerId, agentCalcRequest.getMerId());
        }
        checkWrapper.eq(UserAgent::getIsDel, 0);
        checkWrapper.orderByAsc(UserAgent::getCreateTime);
        return list(checkWrapper);
    }


    private BrandAgentItems getBrokerageConfig(BrandAgentRegion brandAgentRegion, Integer brandId, Integer agentConfigCategoryId) {
        LambdaQueryWrapper<BrandAgentItems> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BrandAgentItems::getAgentReginId, brandAgentRegion.getId());
        lqw.eq(BrandAgentItems::getCategoryId, agentConfigCategoryId);
        lqw.eq(BrandAgentItems::getIsDel, 0);
        lqw.eq(BrandAgentItems::getStatus, 1);
        lqw.eq(BrandAgentItems::getBrandId, brandId);
        return brandAgentItemsService.getOne(lqw);
    }

    private List<UserAgent> addAgentList(AgentCalcRequest agentCalcRequest, OrderDetail orderDetail, int level, TreeMap<Integer, BigDecimal> brokerageLevel) {
        List<UserAgent> districtUserList = userAgentService.getByRegion(agentCalcRequest, level);
        if (CollUtil.isEmpty(districtUserList)) {
            // 要给区级代理分佣
            BrandAgentItems brandAgentItems = getDistrictAgentConfig(agentCalcRequest, level);
            if (null != brandAgentItems) {
                brokerageLevel.put(level, brandAgentItems.getBrokerage());
            }
        }
        return districtUserList;
    }

    private BrandAgentItems getDistrictAgentConfig(AgentCalcRequest agentCalcRequest, Integer regionType) {
        LambdaQueryWrapper<BrandAgentRegion> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(BrandAgentRegion::getRegionId, agentCalcRequest.getDistrictId());
        checkWrapper.eq(BrandAgentRegion::getRegionType, regionType);
        checkWrapper.eq(BrandAgentRegion::getIsDel, 0);
        checkWrapper.eq(BrandAgentRegion::getBrandId, agentCalcRequest.getBrandId());
        BrandAgentRegion brandAgentRegion = brandAgentRegionService.getOne(checkWrapper);
        if (ObjectUtil.isNotNull(brandAgentRegion)) {
            // 分类
            LambdaQueryWrapper<BrandAgentItems> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BrandAgentItems::getAgentReginId, brandAgentRegion.getId());
            lqw.eq(BrandAgentItems::getCategoryId, agentCalcRequest.getAgentConfigCategoryId());
            lqw.eq(BrandAgentItems::getIsDel, 0);
            lqw.eq(BrandAgentItems::getStatus, 1);
            lqw.eq(BrandAgentItems::getBrandId, agentCalcRequest.getBrandId());
            BrandAgentItems brandAgentItems = brandAgentItemsService.getOne(lqw);
            return brandAgentItems;
        }
        return null;
    }

}

